using System;
using System.Dynamic;
using System.Reflection;

namespace Charisma.Common
{
    public class DynamicTypeWrapper : DynamicObject
    {
        private readonly Type type;

        public DynamicTypeWrapper(Type type)
        {
            this.type = type;
        }

        // Handle static properties 
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            PropertyInfo prop = type.GetProperty(binder.Name,
                                                 BindingFlags.FlattenHierarchy | BindingFlags.Static |
                                                 BindingFlags.Public | BindingFlags.NonPublic);
            if (prop == null)
            {
                result = null;
                return false;
            }

            result = prop.GetValue(null, null);
            return true;
        }

        // Handle static methods 
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            MethodInfo method = type.GetMethod(binder.Name,
                                               BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public |
                                               BindingFlags.NonPublic);
            if (method == null)
            {
                result = null;
                return false;
            }

            result = method.Invoke(null, args);
            return true;
        }
    }
}